import { UserModel } from '../model/UserModel';
import { createHash } from 'crypto';

import RedisWrapper from '../redis/RedisWrapper';

class PassPortService {
  async login(username: string, password: string) {
    const user = await UserModel.findOne({
      where: { username },
    });
    if (!user) {
      throw new global.errs.ParameterException('用户名或密码错误', 400);
    }

    if (!user.status) {
      throw new global.errs.ParameterException('用户已停用', 400);
    }
    const pass = createHash('md5').update(password).digest('hex').toString();
    if (user.password !== pass) {
      throw new global.errs.ParameterException('用户名或密码错误', 400);
    }
    await RedisWrapper.set('user_cache_key:' + user.id, user);
    return user;
  }
}

export default new PassPortService();
